<?php

/**
 * 
 * 第三方登录
 * @author xiaozhuge
 *
 */
class third_loginApp extends MallbaseApp {

    var $_third_login_mod;
    var $_third_login_id;

    function __construct() {
        $this->third_loginApp();
    }

    function third_loginApp() {
        parent::__construct();
        $this->_third_login_mod = & m('third_login');
    }

    function qq() {
        $unionid = 0;
        //第三方的名称
        $third_name = 'qq';

        //应用的APPID APPKEY
        $app_id = Conf::get('qq_appid');
        $app_secret = Conf::get('qq_appkey');

        if (empty($app_id) || empty($app_secret)) {
            $this->show_warning('qq_error');
            return;
        }


//成功授权后的回调地址
        $my_url = site_url() . "/index.php?app=third_login&act=qq";

//Step1：获取Authorization Code
        session_start();
        $code = $_REQUEST["code"];
        if (empty($code)) {
            //state参数用于防止CSRF攻击，成功授权后回调时会原样带回
            $_SESSION['state'] = md5(uniqid(rand(), TRUE));
            //拼接URL     
            $dialog_url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id="
                    . $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
                    . $_SESSION['state'];
            echo("<script> top.location.href='" . $dialog_url . "'</script>");
            exit;
        }

        //Step2：通过Authorization Code获取Access Token
        if ($_REQUEST['state'] == $_SESSION['state']) {
            //拼接URL   
            $token_url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&"
                    . "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
                    . "&client_secret=" . $app_secret . "&code=" . $code;

            $response = file_get_contents($token_url);

            if (strpos($response, "callback") !== false) {
                $lpos = strpos($response, "(");
                $rpos = strrpos($response, ")");
                $response = substr($response, $lpos + 1, $rpos - $lpos - 1);
                $msg = json_decode($response);
                if (isset($msg->error)) {
                    echo "<h3>error:</h3>" . $msg->error;
                    echo "<h3>msg  :</h3>" . $msg->error_description;
                    exit;
                }
            }

            //Step3：使用Access Token来获取用户的OpenID
            $params = array();
            parse_str($response, $params);
            $graph_url = "https://graph.qq.com/oauth2.0/me?access_token=" . $params['access_token'];
            $str = file_get_contents($graph_url);
            if (strpos($str, "callback") !== false) {
                $lpos = strpos($str, "(");
                $rpos = strrpos($str, ")");
                $str = substr($str, $lpos + 1, $rpos - $lpos - 1);
            }
            $user = json_decode($str);
            if (isset($user->error)) {
                echo "<h3>error:</h3>" . $user->error;
                echo "<h3>msg  :</h3>" . $user->error_description;
                exit;
            }

            $openid = $user->openid;
            //    echo("Hello " . $user->openid);  这个是唯一的  通过这个判断  用户 是否存在 根据ID值获取相关信息
            $get_user_info_url = "https://graph.qq.com/user/get_user_info?access_token=" . $params['access_token'] . "&oauth_consumer_key=" . $app_id . "&openid=" . $openid;
            $str = file_get_contents($get_user_info_url);
            $qq_user = json_decode($str);

            $this->check_third_login($third_name,$openid,$unionid);
            $this->show_message('login_successed', 'enter_member_center', 'index.php?app=member');
        } else {
            echo("The state does not match. You may be a victim of CSRF.");
        }
    }

    /**
     * 
     * 新浪微博登录
     */
    function sina() {
        //应用的APPID APPKEY
        $sina_app_key = Conf::get('sina_appid');
        $sina_app_secret = Conf::get('sina_appkey');

        if (empty($sina_app_key) || empty($sina_app_secret)) {
            $this->show_warning('qq_error');
            return;
        }

        $redirect_to_login = '/includes/third/sina_api/index.php?sina_app_key=' . $sina_app_key
                . '&sina_app_secret=' . $sina_app_secret;
        header("location:$redirect_to_login");
        exit();
    }

    /**
     * 
     * 新浪微博登录回调
     */
    function sina_callback() {
        $unionid = 0;
        $third_name = 'sina';
        $nickname = isset($_GET["sina_nickname"]) ? $_GET["sina_nickname"] : '';
        $user_id = isset($_GET["sina_user_id"]) ? $_GET["sina_user_id"] : '';
        $openid = $user_id;
        $this->check_third_login($third_name,$openid,$unionid);
        $this->show_message('login_successed', 'enter_member_center', 'index.php?app=member');
    }

    /**
     * PC端微信扫码登录
     */
    function wxlogin_qr() {
        $unionid = 0;
        $third_name = 'weixin'; #微信扫码登录
        $appid = Conf::get('wxlogin_qr_appid');
        $secret = Conf::get('wxlogin_qr_appkey');
        if (empty($appid) || empty($secret)) {
            $this->show_warning('error');
            return;
        }
        $code = $_REQUEST["code"];
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $appid . '&secret=' . $secret . '&code=' . $code . '&grant_type=authorization_code';
        $str = file_get_contents($url);
        $info = json_decode($str);

        $openid = $info->openid;
        $access_token = $info->access_token;

        if (empty($openid) || empty($access_token)) {
            $this->show_message(Lang::get('login_failure'), 'back_before_login', 'index.php?app=member&act=login');
            return;
        }
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid;
        $str = file_get_contents($url);
        $wx_user = json_decode($str);

        if (empty($wx_user->openid)) {
            $this->show_message(Lang::get('login_failure'), 'back_before_login', 'index.php?app=member&act=login');
            return;
        }
        if ($wx_user->unionid) {
            $unionid = $wx_user->unionid;
        }
        $this->check_third_login($third_name,$openid,$unionid);
        $this->show_message('login_successed', 'enter_member_center', 'index.php?app=member');
    }

    
    function check_third_login($third_name, $openid, $unionid = 0) {
        if ($unionid) {
            $conditions = " unionid='$unionid' and third_name='$third_name'";
        } else {
            $conditions = " openid='$openid' and third_name='$third_name'";
        }

        $third_login_mod = & m('third_login');
        $third_login = $third_login_mod->get($conditions);

        $generate_code = rand(10000, 99999);
        $_SESSION['generate_code'] = $generate_code;

        if (empty($third_login)) {
            //添加到third_login表
            $data = array(
                'third_name' => $third_name,
                'openid' => $openid,
                'unionid' => $unionid,
                'user_id' => '0',
                'add_time' => gmtime(),
                'update_time' => gmtime(),
            );
            $third_login_id = $third_login_mod->add($data);
            // 新增后绑定相关用户
        } else {
            $third_login_id = $third_login['id'];
            $data = array(
                'update_time' => gmtime(),
            );
            $third_login_mod->edit($third_login_id, $data);

            if ($third_login["user_id"]) {
                $member_mod = &m('member');
                $member = $member_mod->get($third_login["user_id"]);
                if (empty($member)) {
                    $third_login_mod->edit("id=" . $third_login_id, array('user_id' => 0));
                } else {
                    $this->_do_login($third_login["user_id"]);
                    return;
                }
            }
        }
        if (Conf::get('third_login_register')) {
            //开启自动注册则自动注册
            $this->third_login_register($third_name, $third_login_id);
        } else {
            $this->show_message('Bind_user', 'back_list', 'index.php?app=third_login&act=binding&id=' . $third_login_id . '&generate_code=' . $generate_code);
            exit;
        }
    }
    
    function third_login_register($third_name,$third_login_id)
    {
        $user_name = $third_name.'_'.time().rand(1000, 9999);
        $ms = & ms(); //连接用户中心
        while(!$ms->user->check_username($user_name)) {
            $user_name = $third_name.'_'.time().rand(1000, 9999);
            if ($ms->user->check_username($user_name)) {
                break;
            }
        }
        $user_id = $ms->user->register($user_name, '123456', $user_name."@random.com");
        $third_login_mod = & m('third_login');
        $third_login_mod->edit($third_login_id, array('user_id' => $user_id));
     
            /*用户注册功能后 积分操作*/
            import('integral.lib');
            $integral=new Integral();
            $integral->change_integral_reg($user_id);
//向用户发送默认密码提醒
            $ms =& ms();
            $ms->pm->send(MSG_SYSTEM, $user_id, '', Lang::get('change_password'));
        $this->_do_login($user_id);
        $this->_do_login($user_id);
    }

    
    //第三方登录  与用户进行绑定
    function binding() {
        $generate_code = $_GET['generate_code'];
        $id = empty($_GET['id']) ? 0 : intval($_GET['id']);
        if (!$id) {
            $this->show_warning('Hacking Attempt');
            return;
        }
        if ($generate_code != $_SESSION['generate_code']) {
            $this->show_warning('Hacking Attempt');
            return;
        }
        $third_login = $this->_third_login_mod->get($id);

        if (empty($third_login)) {
            $this->show_warning('Hacking Attempt');
            return;
        }
        $third_name = $third_login['third_name'];
        $third_login_id = $third_login['id'];

        if (!IS_POST) {
            $this->assign('third_login', $third_login);
            $this->display('third_login.binding.html');
        } else {
            if ($this->visitor->has_login) {
                $this->show_warning('has_login');
                exit;
            }
            $binding_type = $_POST['binding_type'];
            //绑定类型
            if ($binding_type == 'register') {
                if ($_POST['password'] != $_POST['password_confirm']) {
                    /* 两次输入的密码不一致 */
                    $this->show_warning('inconsistent_password');
                    exit;
                }
                /* 注册并登陆 */
                $user_name = trim($_POST['user_name']);
                $password = $_POST['password'];
                $email = trim($_POST['email']);
                $passlen = strlen($password);
                $user_name_len = strlen($user_name);
                if ($user_name_len < 3 || $user_name_len > 25) {
                    $this->show_warning('user_name_length_error');
                    exit;
                }
                if ($passlen < 6 || $passlen > 20) {
                    $this->show_warning('password_length_error');
                    exit;
                }
                if (!is_email($email)) {
                    $this->show_warning('email_error');
                    exit;
                }
                $ms = & ms(); //连接用户中心
                $user_id = $ms->user->register($user_name, $password, $email);
                if (!$user_id) {
                    $this->show_warning($ms->user->get_error());
                    exit;
                } else {
            
            /*用户注册功能后 积分操作*/
            import('integral.lib');
$user_mod=& m('member');
            $integral=new Integral();
            $integral->change_integral_reg($user_id);
					if($third_login['scene_id']){
						$user_mod->edit($user_id,'referid='.$third_login['scene_id']);
                                                /*用户注册如果有推荐人，则推荐人增加积分*/
                                                $integral->change_integral_recom(intval($third_login['scene_id']));
					}
                    $this->_third_login_mod->edit($third_login_id, array('user_id' => $user_id));
                    $this->_do_login($user_id);
                    /* 同步登陆外部系统 */
                    $synlogin = $ms->user->synlogin($user_id);
                    $this->show_message('binding_ok', 'back_list', 'index.php');
                }
            } else if ($binding_type == 'login') {
                $user_name = trim($_POST['user_name']);
                $password = $_POST['password'];
                $ms = & ms();
                $user_id = $ms->user->auth($user_name, $password);
                if (!$user_id) {
                    /* 未通过验证，提示错误信息 */
                    $this->show_warning($ms->user->get_error());
                    exit;
                }
                $third_login = $this->_third_login_mod->get("user_id=" . $user_id . " and third_name='" . $third_name . "'");
                if ($third_login) {
                    $this->show_warning('untie', 'back_list', 'index.php?app=member');
                    exit;
                } else {
                    $this->_third_login_mod->edit($third_login_id, array('user_id' => $user_id));
                    $this->_do_login($user_id);
                    $synlogin = $ms->user->synlogin($user_id);
                    $this->show_message('binding_ok', 'back_list', 'index.php');
                }
            }
        }
    }



}
